clear;
x1 = sin(0.8*2*pi*1:40);
x2 = 0.01.*randn(1,80);
signal1 = x1;
signal2 = x2;
x2(1:1+length(x1)-1) = x2(1:1+length(x1)-1) + x1;
n1=length(x1);
n2=length(x2);
N=max(n1,n2);
%padding zeros at the end of smaller sequence
if n2>n1
    x1=[x1 zeros(1,N-n1)];
	signal1 = x1;
    x3=x2;x2=x1;x1=x3;
elseif (n1>n2)
    x2=[x2 zeros(1,N-n2)];
	signal2 = x2;
end
x3=x2;

r = [];
s = [];
for i=1:length(x1)-3
	r(i+1) = x2(i)^2 + 2*x2(i+1)^2 + x2(i+2)^2;
end
x2 = [r 0 0];
for i=1:length(x1)-3
	s(i+1) = x1(i)^2 + 2*x1(i+1)^2 + x1(i+2)^2;
end
x1 = [s 0 0];

y=[];
%shifting and multiplying
tic;
for n=1:N
    y(n)=0;
    for j=1:N
        y(n)=y(n)+x1(j)*x2(j);
    end
    x=x2(N);
   for i=N-1:-1:1%loop for shifting and adding zeros
       x2(i+1)=x2(i);
   end
   x2(1)=0;
   y(n)=y(n)/N;
   
end
toc

subplot(3,1,1);
title('signal2');
plot(signal2);
grid on;
grid minor;
xlabel('time index n');
ylabel('amplitude signal1');
subplot(3,1,2);
title('signal2');
plot(s);
grid on;
grid minor;
xlabel('time index n');
ylabel('amplitude signal2');
n=1:N; %plotting crosscorrelation output
subplot(3,1,3);
plot(n,y);
grid on;
grid minor;
xlabel('time index n');
ylabel('amplitude y');
title('cross correlation of sequence x1 and x2');